import Input from "ant-design-vue/es/input";
import { defineComponent, ref, computed, watch, onMounted } from "vue";

// 验证码组件接口定义
interface CaptchaProps {
  modelValue?: string;
  width?: number;
  height?: number;
  length?: number;
  refreshable?: boolean;
  countdown?: number;
  placeholder?: string;
}

// 生成随机验证码
const generateCaptchaCode = (length: number = 4): string => {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 生成验证码图片
const generateCaptchaImage = (code: string, width: number = 120, height: number = 40): string => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  
  if (!ctx) return '';
  
  canvas.width = width;
  canvas.height = height;
  
  // 绘制背景
  ctx.fillStyle = '#f8f9fa';
  ctx.fillRect(0, 0, width, height);
  
  // 绘制干扰线
  for (let i = 0; i < 6; i++) {
    ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 200)}, ${Math.floor(Math.random() * 200)}, ${Math.floor(Math.random() * 200)})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }
  
  // 绘制验证码文字
  const charWidth = width / code.length;
  for (let i = 0; i < code.length; i++) {
    ctx.fillStyle = `rgb(${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)})`;
    ctx.font = `${Math.floor(height * 0.6)}px Arial`;
    ctx.textBaseline = 'middle';
    ctx.textAlign = 'center';
    
    // 添加文字旋转和偏移
    ctx.save();
    ctx.translate(charWidth * (i + 0.5), height / 2);
    ctx.rotate((Math.random() - 0.5) * 0.4);
    ctx.fillText(code[i], 0, 0);
    ctx.restore();
  }
  
  // 添加噪点
  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`;
    ctx.fillRect(Math.random() * width, Math.random() * height, 1, 1);
  }
  
  return canvas.toDataURL();
};

export default defineComponent({
  name: 'Captcha',
  
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 120
    },
    height: {
      type: Number,
      default: 40
    },
    length: {
      type: Number,
      default: 4
    },
    refreshable: {
      type: Boolean,
      default: true
    },
    countdown: {
      type: Number,
      default: 60
    },
    placeholder: {
      type: String,
      default: '请输入验证码'
    }
  },
  
  emits: ['update:modelValue'],
  
  setup(props: CaptchaProps, { emit }) {
    const inputValue = ref(props.modelValue || '');
    const captchaCode = ref(generateCaptchaCode(props.length));
    const captchaImage = ref('');
    const countdownValue = ref(0);
    const isCounting = ref(false);
    
    // 生成验证码图片
    const refreshCaptcha = () => {
      captchaCode.value = generateCaptchaCode(props.length);
      captchaImage.value = generateCaptchaImage(captchaCode.value, props.width, props.height);
    };
    
    // 开始倒计时
    const startCountdown = () => {
      if (isCounting.value) return;
      
      isCounting.value = true;
      countdownValue.value = props.countdown || 60;
      
      const timer = setInterval(() => {
        countdownValue.value--;
        if (countdownValue.value <= 0) {
          clearInterval(timer);
          isCounting.value = false;
        }
      }, 1000);
    };
    
    // 发送验证码（模拟）
    const sendCaptcha = () => {
      refreshCaptcha();
      startCountdown();
      // 这里可以添加实际的发送验证码逻辑
      console.log('验证码已发送:', captchaCode.value);
    };
    
    // 监听输入值变化
    watch(inputValue, (newValue) => {
      emit('update:modelValue', newValue);
    });
    
    // 监听props变化
    watch(() => props.modelValue, (newValue) => {
      if (newValue !== inputValue.value) {
        inputValue.value = newValue || '';
      }
    });
    
    // 组件挂载时生成验证码
    onMounted(() => {
      refreshCaptcha();
    });
    
    // 计算属性：倒计时显示文本
    const countdownText = computed(() => {
      return isCounting.value ? `${countdownValue.value}s` : '获取验证码';
    });
    
    // 计算属性：是否可点击获取验证码
    const canSendCaptcha = computed(() => {
      return !isCounting.value;
    });
    
    return {
      inputValue,
      captchaImage,
      countdownText,
      canSendCaptcha,
      isCounting,
      refreshCaptcha,
      sendCaptcha
    };
  },
  
  render() {
    return (
      <div class="flex items-center gap-[10px]">
        <Input
          v-model:value={this.inputValue}
          placeholder={this.placeholder}
          class="flex-1"
          maxlength={this.length}
        />
        
        {this.refreshable ? (
          <div class="flex items-center gap-[5px]">
            <div 
              class="relative cursor-pointer"
              onClick={this.refreshCaptcha}
              title="点击刷新验证码"
            >
              <img 
                src={this.captchaImage} 
                alt="验证码" 
                width={this.width}
                height={this.height}
                class="border border-gray-300 rounded"
              />
              <div class="absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity duration-200 bg-black bg-opacity-20 text-white text-xs">
                刷新
              </div>
            </div>
            
            <button
              type="button"
              onClick={this.sendCaptcha}
              disabled={!this.canSendCaptcha}
              class={`
                px-3 py-1 text-sm border rounded transition-colors duration-200
                ${this.canSendCaptcha 
                  ? 'bg-blue-500 text-white border-blue-500 hover:bg-blue-600' 
                  : 'bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed'
                }
              `}
            >
              {this.countdownText}
            </button>
          </div>
        ) : (
          <div 
            class="cursor-pointer"
            onClick={this.refreshCaptcha}
            title="点击刷新验证码"
          >
            <img 
              src={this.captchaImage} 
              alt="验证码" 
              width={this.width}
              height={this.height}
              class="border border-gray-300 rounded"
            />
          </div>
        )}
      </div>
    );
  }
});
